<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryStatisticFormRef" :model="queryStatisticParams" :inline="true">
        <el-form-item label="转账日期" prop="tranDate">
          <el-date-picker
            v-model="queryStatisticParams.tranDate"
            class="!w-[240px]"
            type="monthrange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
            :shortcuts="shortcuts"
            @change="handleCalendarChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQueryStatistic">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetStatisticQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-row :gutter="30">
        <el-col :span="4">
          <div style="text-align: center">
            {{ statisticData?.startDate }} —— {{ statisticData?.endDate }}
            <br />
            <span style="color: red; font-weight: bold; font-size: 24px">
              {{ statisticData?.totalAmount }}
            </span>
          </div>
        </el-col>
        <el-col :offset="2" :span="18">
          <div class="mb-10px">
            <el-button
              v-hasPerm="['stock:stockTransfer:add']"
              type="success"
              @click="handleOpenDialog()"
            >
              <template #icon><Plus /></template>
              新增
            </el-button>
            <el-button
              v-hasPerm="['stock:stockTransfer:delete']"
              type="danger"
              :disabled="removeIds.length === 0"
              @click="handleDelete()"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="4">
          <el-table
            :data="statisticData.monthItemVOList"
            height="400px"
            border
            :header-cell-style="{
              'font-weight': 'bold',
              'font-size': '16px',
              'text-align': 'center',
              color: 'black',
              background: 'rgb(173, 216, 230)',
            }"
            :row-class-name="monthRowClassName"
            @row-click="selectMonth"
          >
            <el-table-column prop="month" label="月份" align="center" />
            <el-table-column prop="amount" label="金额" align="right" :formatter="rounding" />
          </el-table>
        </el-col>
        <el-col :offset="2" :span="18">
          <el-table
            ref="dataTableRef"
            v-loading="loading"
            :data="pageData"
            highlight-current-row
            :header-cell-style="{ 'text-align': 'center' }"
            border
            :row-class-name="tableRowClassName"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="100" align="center" />
            <el-table-column
              v-if="false"
              key="id"
              label="主键"
              prop="id"
              min-width="150"
              align="center"
            />
            <el-table-column
              key="tranDate"
              label="转账日期"
              prop="tranDate"
              min-width="100"
              align="center"
            />
            <el-table-column
              key="amount"
              label="转账金额"
              prop="amount"
              min-width="100"
              align="right"
              :formatter="rounding"
            />
            <el-table-column fixed="right" label="操作" width="220">
              <template #default="scope">
                <el-button
                  v-hasPerm="['stock:stockTransfer:edit']"
                  type="primary"
                  size="small"
                  link
                  @click="handleOpenDialog(scope.row.id)"
                >
                  <template #icon><Edit /></template>
                  编辑
                </el-button>
                <el-button
                  v-hasPerm="['stock:stockTransfer:delete']"
                  type="danger"
                  size="small"
                  link
                  @click="handleDelete(scope.row.id)"
                >
                  <template #icon><Delete /></template>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery()"
          />
        </el-col>
      </el-row>
    </el-card>

    <!-- 银证转账表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="转账日期" prop="tranDate">
          <el-date-picker
            v-model="formData.tranDate"
            class="!w-[240px]"
            type="date"
            placeholder="转账日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="转账金额" prop="amount">
          <el-input-number
            v-model="formData.amount"
            :precision="2"
            :step="1"
            class="!w-[240px]"
            placeholder="0.00"
          >
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "StockTransfer",
  inheritAttrs: false,
});

import StockTransferAPI, {
  StockTransferPageVO,
  StockTransferForm,
  StockTransferPageQuery,
  StockTransferStatisticQuery,
  StockTransferStatistic,
  StockTransferMonthRollup,
} from "@/api/stock/stock-transfer";
import { da } from "element-plus/es/locale";
import { TableColumnCtx } from "element-plus";
import { color } from "echarts";

const queryStatisticFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<StockTransferPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const queryStatisticParams = reactive<StockTransferStatisticQuery>({});

// 银证转账表格数据
const pageData = ref<StockTransferPageVO[]>([]);

// 银证转账统计数据
const statisticData = ref<StockTransferStatistic>({
  startDate: "",
  endDate: "",
  totalAmount: 0.0,
  monthItemVOList: [],
});

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 银证转账表单数据
const formData = reactive<StockTransferForm>({});

// 银证转账表单校验规则
const rules = reactive({
  tranDate: [{ required: true, message: "请输入转账日期", trigger: "blur" }],
  amount: [{ required: true, message: "请输入转账金额", trigger: "blur" }],
});

const shortcuts = [
  {
    text: "本月",
    value: () => {
      let now = new Date();
      let year = now.getFullYear();
      let month = String(now.getMonth() + 1).padStart(2, "0");
      let start = `${year}-${month}-01`;

      let nextMonth = new Date(year, Number(month), 1); // 下个月的第一天
      nextMonth.setDate(nextMonth.getDate() - 1); // 回退一天得到本月最后一天
      let day = String(nextMonth.getDate()).padStart(2, "0"); // 确保日子是两位数
      let end = `${year}-${month}-${day}`;
      return [start, end];
    },
  },
  {
    text: "今年",
    value: () => {
      let now = new Date();
      const start = new Date(now.getFullYear(), 0, 1);
      const end = new Date(now.getFullYear(), 11, 31);
      return [start, end];
    },
  },
  {
    text: "最近6个月",
    value: () => {
      let now = new Date(); // 获取当前日期时间

      // 计算六个月前的月份和年份
      let sixMonthsAgo = new Date();
      sixMonthsAgo.setMonth(now.getMonth() - 6);

      // 六个月前的月份的第一天
      let startDate = new Date(sixMonthsAgo.getFullYear(), sixMonthsAgo.getMonth() + 1, 1);

      // 当前月份的最后一天
      let endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);

      return [startDate, endDate];
    },
  },
  {
    text: "最近一年",
    value: () => {
      let now = new Date(); // 获取当前日期时间

      // 计算十二个月前的月份和年份
      let monthsAgo = new Date();
      monthsAgo.setMonth(now.getMonth() - 12);

      // 十二个月前的月份的第一天
      let startDate = new Date(monthsAgo.getFullYear(), monthsAgo.getMonth() + 1, 1);

      // 当前月份的最后一天
      let endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);

      return [startDate, endDate];
    },
  },
];

const tableRowClassName = ({ row, rowIndex }: { row: StockTransferPageVO; rowIndex: number }) => {
  // 确保 row.amount 不为 undefined 或 null
  const amount = row.amount ?? 0.0;
  if (amount > 0.0) {
    return "error-row";
  } else if (amount < 0.0) {
    return "success-row";
  }
  return "";
};

const monthRowClassName = ({
  row,
  rowIndex,
}: {
  row: StockTransferMonthRollup;
  rowIndex: number;
}) => {
  // 确保 row.amount 不为 undefined 或 null
  const amount = row.amount ?? 0.0;
  if (amount > 0.0) {
    return "month-in-row";
  } else if (amount < 0.0) {
    return "month-out-row";
  }
  return "";
};

function selectMonth(row: Record<string, any>) {
  console.log(row);
  queryParams.pageNum = 1;
  const startDate = row.month + "-01";

  const [yearStr, monthStr] = row.month.split("-");
  const year = parseInt(yearStr, 10);
  const month = parseInt(monthStr, 10);
  const date = new Date(year, month, 0);
  const lastDay = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;

  queryParams.tranDate = [startDate, lastDay];
  handleQuery();
}

// 日期选择后将结束日期改为选择月份的最后一天
function handleCalendarChange() {
  // console.log(queryParams.tranDate);

  if (Array.isArray(queryParams.tranDate) && queryParams.tranDate.length === 2) {
    let date = new Date(queryParams.tranDate[1]);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份需要补零
    const lastDay = new Date(year, date.getMonth() + 1, 0);
    const day = String(lastDay.getDate()).padStart(2, "0"); // 天数也需要补零
    queryParams.tranDate = [queryParams.tranDate[0], `${year}-${month}-${day}`];
  }

  // console.log(queryParams.tranDate);
}

function rounding(row: Record<string, any>, column: TableColumnCtx<any>) {
  return parseFloat(row[column.property]).toFixed(2);
}

function getToday() {
  const date = new Date();
  const year = date.getUTCFullYear();
  const month = String(date.getUTCMonth() + 1).padStart(2, "0");
  const day = String(date.getUTCDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

/** 查询银证转账统计 */
function handleQueryStatistic() {
  StockTransferAPI.getStatistic(queryStatisticParams)
    .then((data) => {
      statisticData.value = data;
    })
    .finally(() => {
      console.log("transfer statistic over!");
    });
}

/** 重置银证转账统计查询 */
function handleResetStatisticQuery() {
  queryStatisticFormRef.value!.resetFields();
  pageData.value = [];
  total.value = 0;
  handleQueryStatistic();
}

/** 查询银证转账 */
function handleQuery() {
  loading.value = true;
  StockTransferAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置银证转账查询 */
function handleResetQuery() {
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开银证转账弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改银证转账";
    StockTransferAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增银证转账";
    formData.tranDate = getToday();
  }
}

/** 提交银证转账表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        StockTransferAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetStatisticQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        StockTransferAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetStatisticQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭银证转账弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除银证转账 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      StockTransferAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetStatisticQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQueryStatistic();
});
</script>

<style scoped>
.el-card :deep(.error-row) td {
  color: var(--el-color-error);
}
.el-card :deep(.success-row) td {
  color: var(--el-color-success);
}

.el-card :deep(.month-in-row) {
  --el-table-tr-bg-color: var(--el-color-error-light-9);
}
.el-card :deep(.month-out-row) {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
